//
//  recordController.swift
//  压岁_IOS
//
//  Created by 梓简王 on 2017/7/14.
//  Copyright © 2017年 梓简王. All rights reserved.
//

import Foundation
import QorumLogs
import Alamofire


class recordController : UIViewController,UITableViewDelegate,UITableViewDataSource,PopMenuDelegate,insertUserIDDelegate,moneyOperationDelegate{
    
//    var delegate:recordControllerDelegate?
    
    //    var pageCountFlag:Int!//标记当前第几页
    
    var rootRole:String!//当前记录的用户角色
    var moneyCount:String!//价格总数 Papyrus
    var insertUserID:PopMenu?
    var moneyOperation:PopMenu?
    var rootImageView:UIImageView?
    var leftImageView:UIImageView?
    var rightImageView:UIImageView?
    var addPageImageView:UIImageView?//添加按钮
    var moneyCountLabel:UILabel?
    var addRoleFlag:String?//添加角色的标记
    var handleMoneyImageView_Common:UIImageView?//普通用户界面添加按钮
    var handleMoneyImageView_Love:UIImageView?//情侣界面添加按钮
    var insertPopView:insertUserIDView?
    var moneyOperationPopView:moneyOperationView?
    let addBtnCenterY = 100 + commonVariable.ROOTVIEWHEIGTH + commonVariable.CHILDVIEWHEIGTH/2
    var handleMoneyImageView_Common_Center:CGPoint = CGPoint(x: Int(commonVariable.SYSTEM_WIDTH/2), y: 100 + commonVariable.ROOTVIEWHEIGTH + commonVariable.CHILDVIEWHEIGTH/2)
    var handleMoneyImageView_Love_Center:CGPoint = CGPoint(x: Int(commonVariable.SYSTEM_WIDTH/2), y: 100 + commonVariable.ROOTVIEWHEIGTH + commonVariable.CHILDVIEWHEIGTH/2)
    
    var plus2minusFlag:Int = 0
    
    var rootImageViewPostion = commonVariable.USERHEADERPOSTION
    var leftImageViewPostion = CGRect(x: commonVariable.ROOTVIEWHEIGTH, y: 50, width: commonVariable.CHILDVIEWHEIGTH, height: commonVariable.CHILDVIEWHEIGTH)
    var rightImageViewPostion = CGRect(x: commonVariable.ROOTVIEWHEIGTH, y: 50 + commonVariable.CHILDVIEWHEIGTH, width: commonVariable.CHILDVIEWHEIGTH, height: commonVariable.CHILDVIEWHEIGTH)
    var moneyCountLabelPosition = CGRect(x: 0, y: 400, width: Int(commonVariable.SYSTEM_WIDTH), height: commonVariable.ROOTVIEWHEIGTH)
    
    var moneyCountLabelCenter = CGPoint(x: Int(commonVariable.SYSTEM_WIDTH/2), y: 50 + commonVariable.ROOTVIEWHEIGTH + commonVariable.CHILDVIEWHEIGTH/2)
    var moneyDetailTablePostion:CGRect = CGRect(x: 0, y: 125 + commonVariable.ROOTVIEWHEIGTH + commonVariable.CHILDVIEWHEIGTH/2, width: Int(commonVariable.SYSTEM_WIDTH), height: Int(commonVariable.SYSTEM_HEIGHT) -  Int(125 + commonVariable.ROOTVIEWHEIGTH + commonVariable.CHILDVIEWHEIGTH/2))
    
    var addPageICONPostion:CGRect = CGRect(x: 0, y: 0, width: 100, height: 100)
    
    var addPageCenter:CGPoint = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: commonVariable.SYSTEM_HEIGHT/2)
    
    var addPageMoveCenter:CGPoint = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: commonVariable.SYSTEM_HEIGHT/4 * 3)
    var addPageRootMoveCenter:CGPoint = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: commonVariable.SYSTEM_HEIGHT/4)
    var addPageRigthMoveCenter:CGPoint = CGPoint(x: commonVariable.SYSTEM_WIDTH/2, y: commonVariable.SYSTEM_HEIGHT/4 * 2)
    var addPage_RootGest:UITapGestureRecognizer?
    var addPage_RightGest:UITapGestureRecognizer?
    var addRoleRightGEST:UITapGestureRecognizer?
    
    var moneyDetailTable:UITableView?
    //刷新标记
    var refreshingFlag:Int = 0
    
    override func viewDidLoad() {
        super.viewDidLoad()
        QL4((commonVariable.LOCAL_USER?.commonRoleType)!)
        switch((commonVariable.LOCAL_USER?.commonRoleType)!){
        case "0":
            self.view.backgroundColor = commonVariable.PAPACOLOR
            break
        case "1":
            self.view.backgroundColor = commonVariable.MAMACOLOR
            break
        case "2":
            self.view.backgroundColor = commonVariable.BABYCOLOR
            break
        default:
            break
        }
        self.moneyCount = (commonVariable.COMMONACCOUNT?.balance)!
        self.rootRole = commonVariable.LOCAL_USER?.commonRoleType!
        refreshCountArr()
//        self.delegate = commonVariable.HOSTCLASS
        self.addRoleRightGEST = UITapGestureRecognizer(target: self, action: "addRoleRight")
        self.initMasterTable()
        self.view.addSubview(self.moneyDetailTable!)
        initCommonPage()
        self.createInsertUserIDPopView()
    }
    //初始化列表
    func initMasterTable(){
        //创建用户资金流向列表
        self.moneyDetailTable = UITableView(frame: moneyDetailTablePostion)
        self.moneyDetailTable?.backgroundColor = UIColor.clearColor()
        self.moneyDetailTable?.separatorStyle = .None
        self.moneyDetailTable?.showsVerticalScrollIndicator = false
        self.moneyDetailTable?.delegate = self
        self.moneyDetailTable?.dataSource = self
    }
    //初始化用户普通账户界面
    func initCommonPage(){
        //初始化主要角色
        rootImageView = UIImageView(frame: rootImageViewPostion)
        leftImageView = UIImageView(frame: leftImageViewPostion)
        rightImageView = UIImageView(frame: rightImageViewPostion)
        let addRoleLeftGEST = UITapGestureRecognizer(target: self, action: "addRoleLeft")
        let addRoleRightGEST = UITapGestureRecognizer(target: self, action: "addRoleRight")
        rootImageView?.userInteractionEnabled = true
        leftImageView?.addGestureRecognizer(addRoleLeftGEST)
        rightImageView?.addGestureRecognizer(addRoleRightGEST)
        leftImageView?.userInteractionEnabled = true
        rightImageView?.userInteractionEnabled = true
        leftImageView?.alpha = commonVariable.ICONALPH
        rightImageView?.alpha = commonVariable.ICONALPH
        QL1(rootRole)
        switch(rootRole){
        case "0":
            rootImageView?.image = UIImage(named: "man")
            leftImageView?.image = UIImage(named: "woman")
            rightImageView?.image = UIImage(named: "baby")
            if(commonVariable.COMMONACCOUNT?.motherID != "0" && commonVariable.COMMONACCOUNT?.motherID != ""){
                leftImageView?.alpha = 1
            }
            if(commonVariable.COMMONACCOUNT?.kidID != "0" && commonVariable.COMMONACCOUNT?.kidID != ""){
                rightImageView?.alpha = 1
            }
            self.view.backgroundColor = commonVariable.PAPACOLOR
            break
        case "1":
            rootImageView?.image = UIImage(named: "woman")
            leftImageView?.image = UIImage(named: "man")
            rightImageView?.image = UIImage(named: "baby")
            if(commonVariable.COMMONACCOUNT?.fatherID != "0" && commonVariable.COMMONACCOUNT?.fatherID != ""){
                leftImageView?.alpha = 1
            }
            if(commonVariable.COMMONACCOUNT?.kidID != "0" && commonVariable.COMMONACCOUNT?.kidID != ""){
                rightImageView?.alpha = 1
            }
            self.view.backgroundColor = commonVariable.MAMACOLOR
            break
        case "2":
            rootImageView?.image = UIImage(named: "baby")
            leftImageView?.image = UIImage(named: "man")
            rightImageView?.image = UIImage(named: "woman")
            if(commonVariable.COMMONACCOUNT?.fatherID != "0" && commonVariable.COMMONACCOUNT?.fatherID != ""){
                leftImageView?.alpha = 1
            }
            if(commonVariable.COMMONACCOUNT?.motherID != "0" && commonVariable.COMMONACCOUNT?.motherID != ""){
                rightImageView?.alpha = 1
            }
            self.view.backgroundColor = commonVariable.BABYCOLOR
            break
        default:
            break
        }
        //初始化总额
        self.moneyCountLabel = UILabel(frame: moneyCountLabelPosition)
        self.moneyCountLabel?.center = moneyCountLabelCenter
        self.moneyCountLabel?.text = self.moneyCount
        self.moneyCountLabel?.font = UIFont(name: commonVariable.NUMBERFONTNAME, size: (self.moneyCount == commonVariable.NOTFORNOTBAND) ? 25 : 40)
        self.moneyCountLabel?.textAlignment = .Center
        self.moneyCountLabel?.textColor = commonVariable.BLUECOLOR
        //初始化添加按钮
        self.handleMoneyImageView_Common = UIImageView(frame: CGRect(x: 0, y: 0, width: commonVariable.CHILDVIEWHEIGTH * 2/3, height: commonVariable.CHILDVIEWHEIGTH * 2/3))
        self.handleMoneyImageView_Common?.center = self.handleMoneyImageView_Common_Center
        self.handleMoneyImageView_Common?.image = (self.rootRole == "2") ? UIImage(named: "minusMoney") : UIImage(named: "addMoney")
        self.handleMoneyImageView_Common?.addGestureRecognizer(UITapGestureRecognizer(target: self, action: "operationMoney"))
        self.handleMoneyImageView_Common?.userInteractionEnabled = true
        self.view.addSubview(moneyCountLabel!)
        self.view.addSubview(rootImageView!)
        self.view.addSubview(leftImageView!)
        self.view.addSubview(rightImageView!)
        self.view.addSubview(self.handleMoneyImageView_Common!)
    }
    //空白界面点击添加响应事件
    func clickAddPageBtn(){
        if((self.plus2minusFlag % 2) == 0){
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            rootImageView?.center = addPageRootMoveCenter
            rightImageView?.center = addPageRigthMoveCenter
            addPageImageView?.center = addPageMoveCenter
            self.rootImageView?.userInteractionEnabled = true
            self.rootImageView?.alpha = 1
            self.rightImageView?.userInteractionEnabled = true
            self.rightImageView?.alpha = 1
            UIView.commitAnimations()
        }else{
            UIView.beginAnimations(nil, context: nil)
            UIView.setAnimationDuration(1.0)
            rootImageView?.center = addPageCenter
            rightImageView?.center = addPageCenter
            addPageImageView?.center = addPageCenter
            self.rootImageView?.userInteractionEnabled = false
            self.rootImageView?.alpha = 0
            self.rightImageView?.userInteractionEnabled = false
            self.rightImageView?.alpha = 0
            UIView.commitAnimations()
        }
        plus2minusFlag++
    }
    //点击左边的添加角色按钮
    func addRoleLeft(){
        switch(rootRole){
        case "0":
            self.addRoleFlag = "1"
            if(commonVariable.COMMONACCOUNT?.motherID != ""){
                SweetAlert().showAlert("亲", subTitle: "您已经绑定了母亲角色!", style: AlertStyle.Warning)
                return
            }
            break
        case "1":
            self.addRoleFlag = "0"
            if(commonVariable.COMMONACCOUNT?.fatherID != ""){
                SweetAlert().showAlert("亲", subTitle: "您已经绑定了父亲角色!", style: AlertStyle.Warning)
                return
            }
            break
        case "2":
            self.addRoleFlag = "0"
            if(commonVariable.COMMONACCOUNT?.kidID != ""){
                SweetAlert().showAlert("亲", subTitle: "您已经绑定了父亲角色!", style: AlertStyle.Warning)
                return
            }
            break
        default:
            break
        }
        popAddUserController()
    }
    //点击右边的添加角色按钮
    func addRoleRight(){
        switch(rootRole){
        case "0":
            self.addRoleFlag = "2"
            if(commonVariable.COMMONACCOUNT?.kidID != ""){
                SweetAlert().showAlert("亲", subTitle: "您已经绑定了孩子角色!", style: AlertStyle.Warning)
                return
            }
            break
        case "1":
            self.addRoleFlag = "2"
            if(commonVariable.COMMONACCOUNT?.kidID != ""){
                SweetAlert().showAlert("亲", subTitle: "您已经绑定了孩子角色!", style: AlertStyle.Warning)
                return
            }
            break
        case "2":
            self.addRoleFlag = "1"
            if(commonVariable.COMMONACCOUNT?.motherID != ""){
                SweetAlert().showAlert("亲", subTitle: "您已经绑定了母亲角色!", style: AlertStyle.Warning)
                return
            }
            break
        default:
            break
        }
        popAddUserController()
    }
    //添加用户界面弹出控制
    func popAddUserController(){
        //        SweetAlert().showAlert("宝贝儿", subTitle: "你是不是准备添加标记为\(self.addRoleFlag!)", style: AlertStyle.Success)
        switch(self.addRoleFlag!){
        case "0":
            self.insertPopView?.userTelTextView?.placeholder = "请输入父亲角色的手机"
            break
        case "1":
            self.insertPopView?.userTelTextView?.placeholder = "请输入母亲角色的手机"
            break
        case "2":
            self.insertPopView?.userTelTextView?.placeholder = "请输入孩子角色的手机"
            break
        default:
            break
        }
        self.insertPopView?.role = self.addRoleFlag!
        self.insertUserID?.showMenuView()
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        QL1(commonVariable.CURRENTPAGE)
    }
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
    }
    //MARK :- 资金列表代理
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let reUseString = "masterCell_\(indexPath.row)"
        var cell = moneyCountCell(style: UITableViewCellStyle.Default, reuseIdentifier: reUseString,index: indexPath.row,model:commonVariable.accountArr[indexPath.row])
        return cell
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
        let model:commonAccountRecord = commonVariable.accountArr[indexPath.row]
        SweetAlert().showAlert("\((model.recordType == "0") ? "+" : "-") \((model.operationMoney)!)", subTitle: (model.recordRemark)!, style: AlertStyle.None)
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat {
        return 44
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return commonVariable.accountArr.count
    }
    func scrollViewDidScroll(scrollView: UIScrollView) {
        let sg = scrollView.contentOffset.y
        if sg < -60 {
            self.handleMoneyImageView_Common?.image = UIImage(named: "refreshIcon")
            if(refreshingFlag == 0){
                refreshCountArr()
                self.moneyDetailTable?.reloadData()
            }
            refreshingFlag = 1
        }else{
            refreshingFlag = 0
            self.handleMoneyImageView_Common?.image = (self.rootRole == "2") ? UIImage(named: "minusMoney") : UIImage(named: "addMoney")
        }
    }
    
    //创建popView
    func createInsertUserIDPopView(){
        //创建用户绑定POP
        self.insertPopView = insertUserIDView(frame: CGRect(x: (commonVariable.SYSTEM_WIDTH - commonVariable.HOST_POPVIEW_WEIGHT)/2, y: 20, width: commonVariable.HOST_POPVIEW_WEIGHT, height: commonVariable.HOST_POPVIEW_HEIGHT),role:"父亲")
        self.insertPopView?.delegate = self
        insertUserID = PopMenu(frame: self.view.frame,isDetail: true,detailPage: self.insertPopView!)
        insertUserID!.isShowDetail = true
        insertUserID!.delegate = self
        self.view.addSubview(insertUserID!)
        //创建用户输入金额POP
        self.moneyOperationPopView = moneyOperationView(frame: CGRect(x: (commonVariable.SYSTEM_WIDTH - commonVariable.HOST_POPVIEW_WEIGHT)/2, y: 20, width: commonVariable.HOST_POPVIEW_WEIGHT, height: commonVariable.HOST_POPVIEW_HEIGHT))
        self.moneyOperationPopView?.delegate = self
        moneyOperation = PopMenu(frame: self.view.frame,isDetail: true,detailPage: self.moneyOperationPopView!)
        moneyOperation!.isShowDetail = true
        moneyOperation!.delegate = self
        self.view.addSubview(moneyOperation!)
    }
    //用户操作金钱
    func operationMoney(){
        if(commonVariable.COMMONACCOUNT?.id == ""){
            SweetAlert().showAlert("请先与父亲用户绑定哦！")
            return
        }
        self.moneyOperation?.showMenuView()
    }
    func didClickMenu(index: Int){
        self.insertPopView?.userCheckNo?.resignFirstResponder()
        self.insertPopView?.userTelTextView?.resignFirstResponder()
    }
    func backToPage(popView:UIView){
        self.insertPopView?.userCheckNo?.resignFirstResponder()
        self.insertPopView?.userTelTextView?.resignFirstResponder()
    }
    func checkSuccessAction(){
        self.insertUserID?.hideMenuView()
        commonVariable.HOSTCLASS!.closeLeft()
        if(commonVariable.LOGINVIEW == nil){
            commonVariable.LOGINVIEW = UIStoryboard(name: "LoginView", bundle: nil).instantiateInitialViewController() as! loginViewController
            commonVariable.HOSTCLASS?.presentViewController(commonVariable.LOGINVIEW!, animated: true, completion: { () -> Void in
                
            })
        }else{
            commonVariable.HOSTCLASS?.dismissViewControllerAnimated(true, completion: { () -> Void in
            })
        }
    }
    //刷新操作数组
    func refreshCountArr(){
        if(commonVariable.COMMONACCOUNT!.id == ""){
            SweetAlert().showAlert("亲", subTitle: "请与父亲用户绑定！", style: AlertStyle.Warning)
            return
        }
        self.view.userInteractionEnabled = false
        commonVariable.LOADING_PACMAN.center = commonVariable.WINDOWSCENTER
        self.view.addSubview(commonVariable.LOADING_PACMAN)
        commonVariable.LOADING_PACMAN.startAnimation()
        QL1(["AccountID":"\((commonVariable.COMMONACCOUNT!.id)!)"])
        Alamofire.request(.POST, commonVariable.GETCOMMONACCOUNT,parameters:["AccountID":"\((commonVariable.COMMONACCOUNT!.id)!)"],headers:nil).responseJSON() {
            response in
            self.view.userInteractionEnabled = true
            commonVariable.LOADING_PACMAN.stopAnimation()
            commonVariable.LOADING_PACMAN.removeFromSuperview()
            guard let JSONDIC = response.result.value else {
                QL4(response.result.error)
                switch response.result.error!.code {
                case -1009 :
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                case 3840:
                    SweetAlert().showAlert("对不起", subTitle: "服务出现故障，请联系管理员", style: AlertStyle.Error)
                case -1001 :
                    
                    SweetAlert().showAlert("对不起", subTitle: "上传信息超时", style: AlertStyle.Error)
                default:
                    SweetAlert().showAlert("对不起", subTitle: "请检查您的网络配置", style: AlertStyle.Error)
                }
                return }
            QL2(JSONDIC)
            let resultDict = JSONDIC as? NSDictionary
            let jsonObj = JSON(JSONDIC)
            let errorCode = jsonObj["errorcode"].intValue
            let errorMsg = jsonObj["message"].stringValue
            QL4(commonVariable.accountArr)
            QL2(errorMsg)
            if errorCode != 1 {
                SweetAlert().showAlert("对不起", subTitle: "\(errorMsg)", style: AlertStyle.Warning)
            }else{
                let countArr = jsonObj["commonAccountRecordList"].arrayValue
                let commonAccountList = jsonObj["commonAccountList"].dictionaryObject
                commonVariable.COMMONACCOUNT = commonAccount.parse(dict: commonAccountList!)
                self.moneyCountLabel?.text = (commonVariable.COMMONACCOUNT?.balance)!
                //普通账户信息
                let accountDataDic:NSMutableDictionary = NSMutableDictionary()
                commonVariable.accountArr = []
                for item in countArr {
                    commonVariable.accountArr.append(commonAccountRecord.parse(dict: item.dictionaryObject!))
                }
                //更新记录内容
                self.moneyDetailTable?.reloadData()
            }
        }
    }
    //弹出框代理
    func moneyOperation(moneyString: String, operationDetail: String) {
        self.moneyOperation?.hideMenuView()
        refreshCountArr()
    }
}